import random
import string
from PIL import Image, ImageDraw, ImageFont
from django.core.cache import cache


# 验证码生成
class CaptchaTool:
    """
    生成验证码图片
    """

    def generate_captcha_text(self, length=4):
        """生成随机验证码文本"""
        characters = string.ascii_uppercase + string.digits
        return "".join(random.choice(characters) for _ in range(length))

    def generate_captcha_image(self, text):
        """生成验证码图片"""
        width, height = 120, 40
        image = Image.new("RGB", (width, height), color=(255, 255, 255))
        draw = ImageDraw.Draw(image)

        # 添加干扰线
        for _ in range(5):
            x1 = random.randint(0, width)
            y1 = random.randint(0, height)
            x2 = random.randint(0, width)
            y2 = random.randint(0, height)
            draw.line(
                [(x1, y1), (x2, y2)],
                fill=(
                    random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255),
                ),
            )

        # 添加干扰点
        for _ in range(100):
            x = random.randint(0, width)
            y = random.randint(0, height)
            draw.point(
                (x, y),
                fill=(
                    random.randint(0, 255),
                    random.randint(0, 255),
                    random.randint(0, 255),
                ),
            )

        # 绘制验证码文本
        try:
            font = ImageFont.truetype("arial.ttf", 28)
        except IOError:
            font = ImageFont.load_default()

        text_width = draw.textlength(text, font=font)
        text_x = (width - text_width) / 2
        text_y = 5

        for i, char in enumerate(text):
            x = text_x + i * (text_width / len(text))
            y = text_y + random.randint(-3, 3)
            draw.text(
                (x, y),
                char,
                font=font,
                fill=(
                    random.randint(0, 100),
                    random.randint(0, 100),
                    random.randint(0, 100),
                ),
            )

        return image

    def verify_captcha(self, captcha_key, code):
        """验证验证码"""
        return cache.get(f"captcha:{captcha_key}") == code
